<?php
namespace app\controller;

use think\Request;
use app\BaseController;
use app\model\Reminder;
use app\model\OperationLog;
use think\facade\View;
use DateTime;
use app\model\Project;

class ReminderController extends BaseController
{
    /**
     * 创建提醒（通过日期）
     */
    public function addReminder(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['title'])) {
            return json(['status' => 400, 'message' => '提醒标题不能为空']);
        }
        if (empty($data['due_date'])) {
            return json(['status' => 400, 'message' => '提醒时间不能为空']);
        }

        return $this->createReminder($user, $data);
    }

    /**
     * 创建提醒（通过时间偏移）
     */
    public function addReminderByOffset(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['title'])) {
            return json(['status' => 400, 'message' => '提醒标题不能为空']);
        }

        // 验证时间偏移量
        $timeOffset = $data['time_offset'];
        if (!is_numeric($timeOffset) || $timeOffset <= 0) {
            return json(['status' => 400, 'message' => '时间偏移量必须是大于0的数字']);
        }

        // 计算提醒时间
        $dueTime = time() + intval($timeOffset);
        $data['due_date'] = date('Y-m-d H:i:s', $dueTime);
        unset($data['time_offset']);  // 移除time_offset参数

        return $this->createReminder($user, $data);
    }

    /**
     * 创建提醒的公共方法
     * @param User $user 用户对象
     * @param array $data 提醒数据
     * @return \think\response\Json
     */
    private function createReminder($user, $data)
    {
        try {
            // 验证提醒时间
            $dueTime = strtotime($data['due_date']);
            if ($dueTime === false) {
                return json(['status' => 400, 'message' => '提醒时间格式不正确']);
            }
            if ($dueTime < time()) {
                return json([
                    'status' => 400,
                    'message' => '提醒时间不能早于当前时间',
                    'current_time' => date('Y-m-d H:i:s'),
                    'due_time' => $data['due_date']
                ]);
            }

            // 验证循环规则
            // if (!empty($data['is_recurring'])) {
            //     if (empty($data['recurrence_rule'])) {
            //         return json(['status' => 400, 'message' => '循环提醒必须设置循环规则']);
            //     }
            //     if (!in_array($data['recurrence_rule'], ['daily', 'weekly', 'monthly', 'yearly'])) {
            //         return json(['status' => 400, 'message' => '无效的循环规则']);
            //     }
            // }
            $is_rescurring = 0;
            if (!empty($data['recurrence_rule'])) {
                if (in_array($data['recurrence_rule'], ['daily', 'weekly', 'monthly', 'yearly'])) {
                    $is_rescurring=1;
                }
            }

            $recurrence_end_date = null;
            if (!empty($data['recurrence_end_date']) && $data['recurrence_end_date'] !== '') {
                $recurrence_end_date = $data['recurrence_end_date'];
            }
            

            // 创建提醒
            $reminder = new Reminder;
            $reminder->user_id = $user->id;
            $reminder->title = $data['title'];
            $reminder->description = $data['description'] ?? '';
            $reminder->due_date = $data['due_date'];
            $reminder->is_recurring = $is_rescurring;
            $reminder->recurrence_rule = $data['recurrence_rule'] ?? null;
            $reminder->recurrence_end_date = $recurrence_end_date;

            // 处理项目关联
            if (isset($data['project_id'])) {
                if ($data['project_id'] === 'A') {
                    // AI自动判断项目
                    $projectId = $this->autoDetectProject($data['title'], $data['description'] ?? '');
                    $reminder->project_id = $projectId;
                    if ($projectId) {
                        $reminder->recordAiHistory('auto_project', "AI自动关联到项目ID: {$projectId}");
                    }
                } else {
                    $reminder->project_id = $data['project_id'];
                }
            }

            $reminder->save();

            // 记录操作日志
            UserController::logOperation($user->id, 'create_reminder', "创建提醒：{$data['title']}", new Request());

            return json([
                'status' => 200,
                'message' => '提醒创建成功',
                'data' => $reminder
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('创建提醒失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '创建提醒失败，请稍后重试']);
        }
    }

    /**
     * 使用AI判断提醒所属项目
     * @param Reminder $reminder 提醒对象
     * @param int $userId 用户ID
     * @return int|null 项目ID或null
     */
    private function determineProjectByAI($reminder, $userId)
    {
        try {
            // 获取用户的所有进行中的项目
            $projects = Project::where('user_id', $userId)
                ->where('status', Project::STATUS_ONGOING)
                ->select();

            if ($projects->isEmpty()) {
                return null;
            }

            // TODO: 这里添加实际的AI判断逻辑
            // 可以基于以下因素：
            // 1. 提醒标题和描述与项目名称、目标的相似度
            // 2. 提醒时间是否在项目周期内
            // 3. 历史提醒的项目分配模式
            // 4. 关键词匹配
            // 暂时返回null，等待AI功能实现
            return null;

        } catch (\Exception $e) {
            \think\facade\Log::error('AI判断项目失败：' . $e->getMessage());
            return null;
        }
    }

    /**
     * 验证提醒操作权限
     */
    private function verifyReminderOperation(Request $request, $reminderId)
    {
        // 先尝试用户验证
        $user = $this->verifyUser($request);
        if ($user) {
            $reminder = Reminder::where('id', $reminderId)
                ->where('user_id', $user->id)
                ->find();
            if ($reminder) {
                return ['reminder' => $reminder, 'user' => $user];
            }
        }

        // 尝试操作密钥验证（从 GET 参数获取）
        $operationKey = $request->param('key');
        if ($operationKey) {
            $reminder = Reminder::where('id', $reminderId)
                ->where('operation_key', $operationKey)
                ->find();
            if ($reminder) {
                return ['reminder' => $reminder, 'user' => null];
            }
        }

        return null;
    }

    /**
     * 标记提醒事项完成
     */
    public function markReminderCompleted(Request $request)
    {
        $reminderId = $request->param('reminder_id');
        $result = $this->verifyReminderOperation($request, $reminderId);
        
        if (!$result) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminder = $result['reminder'];
        $user = $result['user'];

        try {
            // 标记当前提醒已处理
            $reminder->is_completed = 1;

            // 处理循环提醒
            if ($reminder->is_recurring) {
                // 计算下次提醒时间
                $nextDueDate = $this->calculateNextDueDate($reminder->due_date, $reminder->recurrence_rule);
                
                // 检查是否超过结束日期
                if ($reminder->recurrence_end_date && $nextDueDate > $reminder->recurrence_end_date) {
                    $reminder->is_finished = 1;
                } else {
                    $reminder->due_date = $nextDueDate;
                    $reminder->is_completed = 0;  // 重置完成状态
                }
            } else {
                // 非循环提醒直接标记为完结
                $reminder->is_finished = 1;
            }

            $reminder->save();

            // 记录操作日志（如果是用户操作）
            if ($user) {
                UserController::logOperation($user->id, 'complete_reminder', "完成提醒事项：{$reminder->title}", $request);
            }

            return json(['status' => 200, 'message' => '提醒事项标记为已完成']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '操作失败：' . $e->getMessage()]);
        }
    }

    /**
     * 计算下次提醒时间
     */
    private function calculateNextDueDate($currentDueDate, $recurrenceRule)
    {
        $date = new DateTime($currentDueDate);
        
        switch ($recurrenceRule) {
            case 'daily':
                $date->modify('+1 day');
                break;
            case 'weekly':
                $date->modify('+1 week');
                break;
            case 'monthly':
                $date->modify('+1 month');
                break;
            case 'yearly':
                $date->modify('+1 year');
                break;
            default:
                // 处理自定义规则，例如 "FREQ=WEEKLY;BYDAY=MO,WE,FR"
                if (strpos($recurrenceRule, 'FREQ=') === 0) {
                    // 这里可以添加更复杂的循环规则解析
                    // 例如：每周一三五、每月1号和15号等
                }
                break;
        }

        return $date->format('Y-m-d H:i:s');
    }

    /**
     * 获取提醒事项列表
     */
    public function getReminderList(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $page = $request->param('page', 1);
        $pageSize = $request->param('page_size', 10);
        $showCompleted = $request->param('show_completed', 0);
        $is_recurring = $request->param('is_recurring');
        if ($showCompleted == false) {
            $showCompleted = 0;
        } else {
            $showCompleted = 1;
        }

        try {
            $query = Reminder::where('user_id', $user->id);

            if ($showCompleted == 0) {
                $query->where('is_finished', 0)
                    ->where('is_completed', 0)
                    ->where('is_disabled', 0);
            } else {
                $query->where(function ($inner_query) {
                    $inner_query->where('is_disabled', 1)
                    ->WhereOr('is_finished', 1)
                    ->WhereOr('is_completed', 1);
                });
            }
            if (isset($is_recurring)) {
                if ($is_recurring == 1) {
                    $query->where('is_recurring', 1);
                } else if ($is_recurring == 0) {
                    $query->where('is_recurring', 0);
                }
            }

            $reminders = $query->order('due_date', 'asc')
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $page
                ]);

            return json([
                'status' => 200,
                'message' => '获取成功',
                'data' => [
                    'total' => $reminders->total(),
                    'current_page' => $reminders->currentPage(),
                    'last_page' => $reminders->lastPage(),
                    'reminders' => $reminders->items()
                ]
            ]);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '获取失败：' . $e->getMessage()]);
        }
    }

    /**
     * 禁用提醒事项
     */
    public function disableReminder(Request $request)
    {
        $reminderId = $request->param('reminder_id');
        $result = $this->verifyReminderOperation($request, $reminderId);
        
        if (!$result) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminder = $result['reminder'];
        $user = $result['user'];

        try {
            $reminder->is_disabled = 1;
            $reminder->save();

            // 记录操作日志（如果是用户操作）
            if ($user) {
                UserController::logOperation($user->id, 'disable_reminder', "禁用提醒事项：{$reminder->title}", $request);
            }

            return json(['status' => 200, 'message' => '提醒事项禁用成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '禁用失败：' . $e->getMessage()]);
        }
    }

    /**
     * 添加备注
     */
    public function addNote(Request $request)
    {
        $reminderId = $request->param('reminder_id');
        $result = $this->verifyReminderOperation($request, $reminderId);
        
        if (!$result) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminder = $result['reminder'];
        $user = $result['user'];

        $notes = $request->param('notes');
        if (empty($notes)) {
            return json(['status' => 400, 'message' => '备注内容不能为空']);
        }

        try {
            $reminder->notes = $notes;
            $reminder->save();

            // 记录操作日志（如果是用户操作）
            if ($user) {
                UserController::logOperation($user->id, 'add_note', "添加提醒事项备注：{$reminder->title}", $request);
            }

            return json(['status' => 200, 'message' => '备注添加成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '添加备注失败：' . $e->getMessage()]);
        }
    }

    /**
     * 删除提醒事项
     */
    public function deleteReminder(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminderId = $request->param('reminder_id');
        
        $reminder = Reminder::where('id', $reminderId)
            ->where('user_id', $user->id)
            ->find();

        if (!$reminder) {
            return json(['status' => 400, 'message' => '提醒事项不存在或无权限操作']);
        }

        try {
            // 软删除提醒事项
            $reminder->delete();

            // 使用 UserController 的日志记录方法
            UserController::logOperation($user->id, 'delete_reminder', "删除提醒事项：{$reminder->title}", $request);

            return json(['status' => 200, 'message' => '提醒事项删除成功']);
        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 验证用户权限
     */
    private function verifyUser(Request $request)
    {
        // 优先尝试 Token 验证
        $user = UserController::getUserFromToken($request);
        if ($user) {
            return $user;
        }

        // 尝试 reminder_key 验证
        $reminderKey = $request->header('X-Reminder-Key');
        if ($reminderKey) {
            $user = \app\model\User::where('reminder_key', $reminderKey)
                ->where('is_verified', 1)
                ->find();
            if ($user) {
                return $user;
            }
        }

        return null;
    }

    /**
     * 延后提醒
     */
    public function postponeReminder(Request $request)
    {
        $reminderId = $request->param('reminder_id');
        $result = $this->verifyReminderOperation($request, $reminderId);
        
        if (!$result) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminder = $result['reminder'];
        $user = $result['user'];

        // 获取延后时间
        $postponeTime = $request->param('postpone_time');
        if (empty($postponeTime)) {
            return json(['status' => 400, 'message' => '延后时间不能为空']);
        }

        try {
            // 计算新的醒时间
            $newDueDate = null;
            $currentTime = time();

            if (strtotime($postponeTime) !== false) {
                // 如果是具体的时间格式
                $newDueDate = strtotime($postponeTime);
            } else {
                // 如果是相对时间格式（如：+30minutes, +1hour, +1day）
                $newDueDate = strtotime($postponeTime, strtotime($reminder->due_date));
            }

            // 验证新的醒时间
            if ($newDueDate === false) {
                return json(['status' => 400, 'message' => '延后时间格式不正确']);
            }

            if ($newDueDate <= $currentTime) {
                return json([
                    'status' => 400,
                    'message' => '延后时间必须晚于当前时间',
                    'current_time' => date('Y-m-d H:i:s', $currentTime),
                    'postpone_time' => date('Y-m-d H:i:s', $newDueDate)
                ]);
            }

            // 保存原始时间用于日志
            $originalDueDate = $reminder->due_date;

            // 更新提醒时间
            $reminder->due_date = date('Y-m-d H:i:s', $newDueDate);
            $reminder->is_finished = 0;  // 重置完结状态
            $reminder->is_completed = 0; // 重置完成状态
            $reminder->save();

            // 记录操作日志（如果是用户操作）
            if ($user) {
                UserController::logOperation(
                    $user->id, 
                    'postpone_reminder', 
                    "延后提醒事项：{$reminder->title} 从 {$originalDueDate} 到 {$reminder->due_date}",
                    $request
                );
            }

            return json([
                'status' => 200,
                'message' => '提醒延后成功',
                'data' => [
                    'reminder_id' => $reminder->id,
                    'title' => $reminder->title,
                    'original_due_date' => $originalDueDate,
                    'new_due_date' => $reminder->due_date
                ]
            ]);

        } catch (\Exception $e) {
            return json(['status' => 500, 'message' => '延后失败：' . $e->getMessage()]);
        }
    }

    /**
     * 备注页面（包含所有操作）
     */
    public function noteReminderPage(Request $request)
    {
        $reminderId = $request->param('reminder_id');
        $key = $request->param('key');
        
        if (empty($reminderId) || empty($key)) {
            return '<h1>无效的操作链接</h1>';
        }

        $reminder = Reminder::where('id', $reminderId)
            ->where('operation_key', $key)
            ->find();

        if (!$reminder) {
            return '<h1>提醒不存在或链接已失效</h1>';
        }

        View::assign([
            'reminder' => $reminder,
            'operation_key' => $key
        ]);

        return View::fetch('reminder/note');
    }

    /**
     * 延后提醒页面
     */
    public function postponeReminderPage(Request $request)
    {
        $reminderId = $request->param('reminder_id');
        $key = $request->param('key');
        
        if (empty($reminderId) || empty($key)) {
            return '<h1>无效的操作链接</h1>';
        }

        $reminder = Reminder::where('id', $reminderId)
            ->where('operation_key', $key)
            ->find();

        if (!$reminder) {
            return '<h1>提醒不存在或链接已失效</h1>';
        }

        View::assign([
            'reminder' => $reminder,
            'operation_key' => $key
        ]);

        return View::fetch('reminder/postpone');
    }

    /**
     * 标记完成页面
     */
    public function completeReminderPage(Request $request)
    {
        $reminderId = $request->param('reminder_id');
        $key = $request->param('key');
        
        if (empty($reminderId) || empty($key)) {
            return '<h1>无效的操作链接</h1>';
        }

        $reminder = Reminder::where('id', $reminderId)
            ->where('operation_key', $key)
            ->find();

        if (!$reminder) {
            return '<h1>提醒不存在或链接已失效</h1>';
        }

        View::assign([
            'reminder' => $reminder,
            'operation_key' => $key
        ]);

        return View::fetch('reminder/complete');
    }

    /**
     * 获取系统当前时间
     */
    public function getCurrentTime()
    {
        try {
            $now = time();
            return json([
                'status' => 200,
                'data' => [
                    'timestamp' => $now,
                    'datetime' => date('Y-m-d H:i:s', $now),
                    'date' => date('Y-m-d', $now),
                    'time' => date('H:i:s', $now),
                    'timezone' => date_default_timezone_get(),
                    'week_day' => date('N', $now),  // 1-7 表示周一到周日
                    'week_name' => date('l', $now), // 星期几的英文全称
                    'is_dst' => date('I', $now)     // 是否夏令时
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'status' => 500,
                'message' => '获取系统时间失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 智能创建提醒
     */
    public function addReminderSmart(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $data = $request->post();
        
        // 验证必填字段
        if (empty($data['title'])) {
            return json(['status' => 400, 'message' => '提醒标题不能为空']);
        }
        if (empty($data['due_date'])) {
            return json(['status' => 400, 'message' => '提醒时间不能为空']);
        }

        try {
            // 解析时间字符串
            $dueDate = $this->parseDueDate($data['due_date']);
            if ($dueDate === false) {
                return json(['status' => 400, 'message' => '无法解析提醒时间格式']);
            }

            // 使用解析后的时间创建提醒
            $data['due_date'] = $dueDate;
            return $this->createReminder($user, $data);

        } catch (\Exception $e) {
            \think\facade\Log::error('智能创建提醒失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '创建提醒失败：' . $e->getMessage()]);
        }
    }

    /**
     * 智能解析时间字符串
     */
    private function parseDueDate($timeStr)
    {
        // 先处理相对日期描述
        $relativeDate = $this->parseRelativeDate($timeStr);
        if ($relativeDate !== false) {
            return $relativeDate;
        }

        // 先处理自然语言时间偏移
        $offset = $this->parseTimeOffset($timeStr);
        if ($offset !== false) {
            $now = new DateTime();
            $now->modify("+{$offset} seconds");
            return $now->format('Y-m-d H:i:s');
        }

        // 当前时间
        $now = new DateTime();
        $target = clone $now;
        $hasSetDate = false;
        $hasSetTime = false;

        // 1. 处理标准格式日期
        if (preg_match('/^\d{4}[-年]\d{1,2}[-月]\d{1,2}/', $timeStr)) {
            $date = date_parse($timeStr);
            if ($date['year'] && $date['month'] && $date['day']) {
                $target->setDate($date['year'], $date['month'], $date['day']);
                $hasSetDate = true;
            }
        }
        // 2. 处理月日格式（3月16日）
        elseif (preg_match('/(\d{1,2})月(\d{1,2})[日号]/', $timeStr, $matches)) {
            $month = intval($matches[1]);
            $day = intval($matches[2]);
            $year = $target->format('Y');
            // 如果日期已过，可能需要调整到明年
            $tempDate = clone $target;
            $tempDate->setDate($year, $month, $day);
            if ($tempDate < $now) {
                $year++;
            }
            $target->setDate($year, $month, $day);
            $hasSetDate = true;
        }
        // 3. 处理"本月"格式
        elseif (preg_match('/(本|这个?)月(\d{1,2})[日号]/', $timeStr, $matches)) {
            $target->setDate($target->format('Y'), $target->format('m'), intval($matches[2]));
            $hasSetDate = true;
        }
        // 4. 处理"下个月"格式
        elseif (preg_match('/下个?月(\d{1,2})[日号]/', $timeStr, $matches)) {
            $target->modify('first day of next month');
            $target->setDate($target->format('Y'), $target->format('m'), intval($matches[1]));
            $hasSetDate = true;
        }
        // 5. 处理纯数字日期（15号、17日）
        elseif (preg_match('/(\d{1,2})[日号]/', $timeStr, $matches)) {
            $day = intval($matches[1]);
            $tempDate = clone $target;
            $tempDate->setDate($tempDate->format('Y'), $tempDate->format('m'), $day);
            if ($tempDate < $now) {
                $tempDate->modify('+1 month');
            }
            $target = $tempDate;
            $hasSetDate = true;
        }
        // 6. 处理周几格式
        elseif ($weekday = $this->parseWeekday($timeStr)) {
            if (strpos($timeStr, '下') !== false) {
                // $target->modify('next week');
                // 下周已经处理好了
            } elseif (strpos($timeStr, '本') !== false || strpos($timeStr, '这') !== false) {
                // 本周已经处理好了
            } else {
                // 默认处理为本周，如果已过则自动调整到下周
                $tempDate = clone $target;
                $tempDate->modify($weekday);
                if ($tempDate < $now) {
                    $tempDate->modify('+1 week');
                }
                $target = $tempDate;
            }
            $target->modify($weekday);
            $hasSetDate = true;

            // $date = new DateTime();
            // $weekdayNumber = $date->format('w');
            // throw new \Exception('指定的时间：' . json_encode($target) . '，时间字符串：' . $timeStr . '，当前星期几：' . $weekdayNumber);
        }

        // 处理时间部分
        // 1. 处理标准时间格式（13:20、15:38:40）
        if (preg_match('/(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?/', $timeStr, $matches)) {
            $target->setTime(
                intval($matches[1]),
                intval($matches[2]),
                isset($matches[3]) ? intval($matches[3]) : 0
            );
            $hasSetTime = true;
        }
        // 2. 处理中文时间格式（上午8点、早上8:00）
        elseif (preg_match('/(早上|上午|中午|下午|晚上|夜里|凌晨).*?(\d{1,2})(?:[:点](\d{1,2}))?/', $timeStr, $matches)) {
            $hour = intval($matches[2]);
            $minute = isset($matches[3]) ? intval($matches[3]) : 0;
            
            // 调整时间
            switch ($matches[1]) {
                case '下午':
                    $hour = $hour < 12 ? $hour + 12 : $hour;
                    break;
                case '晚上':
                case '夜里':
                    $hour = $hour < 12 ? $hour + 12 : $hour;
                    break;
            }
            
            $target->setTime($hour, $minute, 0);
            $hasSetTime = true;
        }
        // 3. 处理时间段描述
        elseif ($timeDesc = $this->parseTimeDescription($timeStr)) {
            $target->setTime($timeDesc['hour'], $timeDesc['minute'], 0);
            $hasSetTime = true;
        }

        // 如果没有设置时间，默认为���上8点
        if (!$hasSetTime) {
            $target->setTime(8, 0, 0);
        }

        // 如果时间早于当前时间且未设置具体日期，调整到明天
        if (!$hasSetDate && $target < $now) {
            $target->modify('+1 day');
        }

        return $target->format('Y-m-d H:i:s');
    }

    /**
     * 解析相对日期描述
     */
    private function parseRelativeDate($timeStr)
    {
        $relativeDays = [
            '今天' => '+0 day',
            '今日' => '+0 day',
            '明天' => '+1 day',
            '明日' => '+1 day',
            '后天' => '+2 days',
            '后日' => '+2 days',
            '大后天' => '+3 days',
            '大后日' => '+3 days'
        ];

        $target = null;
        
        // 检查是否包含相对日期描述
        foreach ($relativeDays as $desc => $modify) {
            if (strpos($timeStr, $desc) !== false) {
                $target = new DateTime();
                $target->modify($modify);
                break;
            }
        }

        if ($target === null) {
            return false;
        }

        // 处理时间部分
        // 1. 处理标准时间格式（13:20、15:38:40）
        if (preg_match('/(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?/', $timeStr, $matches)) {
            $target->setTime(
                intval($matches[1]),
                intval($matches[2]),
                isset($matches[3]) ? intval($matches[3]) : 0
            );
        }
        // 2. 处理中文时间格式（上午8点、早上8:00）
        elseif (preg_match('/(早上|上午|中午|下午|晚上|夜里|凌晨).*?(\d{1,2})(?:[:点](\d{1,2}))?/', $timeStr, $matches)) {
            $hour = intval($matches[2]);
            $minute = isset($matches[3]) ? intval($matches[3]) : 0;
            
            // 调整时间
            switch ($matches[1]) {
                case '下午':
                    $hour = $hour < 12 ? $hour + 12 : $hour;
                    break;
                case '晚上':
                case '夜里':
                    $hour = $hour < 12 ? $hour + 12 : $hour;
                    break;
            }
            
            $target->setTime($hour, $minute, 0);
        }
        // 3. 处理时间段描述
        elseif ($timeDesc = $this->parseTimeDescription($timeStr)) {
            $target->setTime($timeDesc['hour'], $timeDesc['minute'], 0);
        }
        // 4. 如果没有指定时间，默认为早上8点
        else {
            $target->setTime(8, 0, 0);
        }

        return $target->format('Y-m-d H:i:s');
    }

    /**
     * 解析自然语言时间偏移
     */
    private function parseTimeOffset($timeStr)
    {
        // 处理偏移量+具体时间的组合格式（如：+30d 13:20）
        if (preg_match('/^\+?(\d+)([yMwdhms])\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/', $timeStr, $matches)) {
            $number = intval($matches[1]);
            $unit = $matches[2];
            $hour = intval($matches[3]);
            $minute = intval($matches[4]);
            $second = isset($matches[5]) ? intval($matches[5]) : 0;
            
            $unitMap = [
                'y' => 'years',
                'M' => 'months',
                'w' => 'weeks',
                'd' => 'days',
                'h' => 'hours',
                'm' => 'minutes',
                's' => 'seconds'
            ];

            if (isset($unitMap[$unit])) {
                $now = new DateTime();
                $now->modify("+{$number} {$unitMap[$unit]}");
                // 设置具体时间
                $now->setTime($hour, $minute, $second);
                return $now->getTimestamp() - time();
            }
        }

        // 处理纯英文简写格式（如：+3d, +5h）
        if (preg_match('/^\+?(\d+)([yMwdhms])$/', $timeStr, $matches)) {
            $number = intval($matches[1]);
            $unit = $matches[2];
            
            $unitMap = [
                'y' => 'years',
                'M' => 'months',
                'w' => 'weeks',
                'd' => 'days',
                'h' => 'hours',
                'm' => 'minutes',
                's' => 'seconds'
            ];

            if (isset($unitMap[$unit])) {
                $now = new DateTime();
                $now->modify("+{$number} {$unitMap[$unit]}");
                return $now->getTimestamp() - time();
            }
        }

        // 处理"+数字+单位"中文格式
        if (preg_match('/^\+?(\d+)(年|月|周|天|日|小时|时|分钟|分)$/', $timeStr, $matches)) {
            $number = intval($matches[1]);
            $unit = $matches[2];
            
            $unitMap = [
                '年' => 'years',
                '月' => 'months',
                '周' => 'weeks',
                '天' => 'days',
                '日' => 'days',
                '小时' => 'hours',
                '时' => 'hours',
                '分钟' => 'minutes',
                '分' => 'minutes'
            ];

            if (isset($unitMap[$unit])) {
                $now = new DateTime();
                $now->modify("+{$number} {$unitMap[$unit]}");
                return $now->getTimestamp() - time();
            }
        }

        // 处理现有的自然语言格式
        $patterns = [
            '/(\d+)年后/' => 'years',
            '/(\d+)个月后/' => 'months',
            '/(\d+)周后/' => 'weeks',
            '/(\d+)天后/' => 'days',
            '/(\d+)小时后/' => 'hours',
            '/(\d+)分钟后/' => 'minutes',
            '/半小时后/' => '30 minutes',
            '/半年后/' => '6 months',
            '/一周后/' => '1 week',
            '/一个月后/' => '1 month',
            '/一年后/' => '1 year',
            '/两年后/' => '2 years'
        ];

        foreach ($patterns as $pattern => $unit) {
            if (preg_match($pattern, $timeStr, $matches)) {
                $value = isset($matches[1]) ? intval($matches[1]) : 1;
                $now = new DateTime();
                $now->modify("+{$value} {$unit}");
                return $now->getTimestamp() - time();
            }
        }

        // 处理纯秒数格式
        if (preg_match('/^\+(\d+)$/', $timeStr, $matches)) {
            return intval($matches[1]);
        }

        return false;
    }

    /**
     * 解析周几描述
     */
    private function parseWeekday($timeStr)
    {
        $weekdayMap = [
            '一' => 'Monday',
            '二' => 'Tuesday',
            '三' => 'Wednesday',
            '四' => 'Thursday',
            '五' => 'Friday',
            '六' => 'Saturday',
            '日' => 'Sunday',
            '天' => 'Sunday'
        ];

        $hasThisOrBen = preg_match('/(这|本)/', $timeStr);
        $hasNext = preg_match('/下/', $timeStr);
        foreach ($weekdayMap as $cn => $en) {
            if (preg_match("/(周|星期|礼拜){$cn}/", $timeStr)) {
                if ($hasThisOrBen) {
                    return 'this week '. $en;
                } elseif ($hasNext) {
                    return 'next week '. $en;
                }
                return $en;
            }
        }

        return false;
    }

    /**
     * 解析时间段描述
     */
    private function parseTimeDescription($timeStr)
    {
        $timeMap = [
            '早上' => ['hour' => 6, 'minute' => 0],
            '早晨' => ['hour' => 8, 'minute' => 0],
            '上午' => ['hour' => 10, 'minute' => 0],
            '中午' => ['hour' => 12, 'minute' => 0],
            '下午' => ['hour' => 14, 'minute' => 0],
            '晚上' => ['hour' => 18, 'minute' => 0],
            '夜里' => ['hour' => 20, 'minute' => 0],
            '半夜' => ['hour' => 22, 'minute' => 0],
            '凌晨' => ['hour' => 4, 'minute' => 0]
        ];

        foreach ($timeMap as $desc => $time) {
            if (strpos($timeStr, $desc) !== false) {
                return $time;
            }
        }

        return false;
    }

    /**
     * 获取提醒详情
     */
    public function detail(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminderId = $request->param('id');
        if (empty($reminderId)) {
            return json(['status' => 400, 'message' => '提醒ID不能为空']);
        }

        try {
            // 获取提醒信息
            $reminder = Reminder::where('id', $reminderId)
                ->where('user_id', $user->id)
                ->find();

            if (!$reminder) {
                return json(['status' => 404, 'message' => '提醒不存在']);
            }

            // 获取关联的项目信息（如果有）
            $project = null;
            if ($reminder->project_id) {
                $project = Project::where('id', $reminder->project_id)->find();
            }

            // 格式化提醒数据
            $data = [
                'id' => $reminder->id,
                'title' => $reminder->title,
                'description' => $reminder->description,
                'due_date' => $reminder->due_date,
                'is_recurring' => $reminder->is_recurring,
                'recurrence_rule' => $reminder->recurrence_rule,
                'recurrence_end_date' => $reminder->recurrence_end_date,
                'is_finished' => $reminder->is_finished,
                'is_completed' => $reminder->is_completed,
                'is_disabled' => $reminder->is_disabled,
                'operation_key' => $reminder->operation_key,
                'created_at' => date('Y-m-d H:i:s', $reminder->created_at),
                'updated_at' => date('Y-m-d H:i:s', $reminder->updated_at),
                'status' => [
                    'is_overdue' => strtotime($reminder->due_date) < time(),
                    'remaining_time' => $this->calculateRemainingTime($reminder->due_date),
                    'status_text' => $this->getReminderStatus($reminder)
                ],
                'project' => $project ? [
                    'id' => $project->id,
                    'name' => $project->name,
                    'status' => $project->status,
                    'status_text' => Project::$statusMap[$project->status] ?? '未知状态'
                ] : null,
                'ai_history' => $reminder->getAiHistoryArray()
            ];

            // 记录操作日志
            UserController::logOperation($user->id, 'view_reminder', "查看提醒：{$reminder->title}", $request);

            return json([
                'status' => 200,
                'data' => $data
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('获取提醒详情失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '获取提醒详情失败：' . $e->getMessage()]);
        }
    }

    /**
     * 计算剩余时间
     */
    private function calculateRemainingTime($dueDate)
    {
        $now = time();
        $dueTime = strtotime($dueDate);
        $diff = $dueTime - $now;

        if ($diff < 0) {
            return '已过期';
        }

        if ($diff < 60) {
            return $diff . '秒';
        }

        if ($diff < 3600) {
            return floor($diff / 60) . '分钟';
        }

        if ($diff < 86400) {
            return floor($diff / 3600) . '小时';
        }

        return floor($diff / 86400) . '天';
    }

    /**
     * 获取提醒状态文本
     */
    private function getReminderStatus($reminder)
    {
        if ($reminder->is_disabled) {
            return '已禁用';
        }
        if ($reminder->is_finished) {
            return '已结束';
        }
        if ($reminder->is_completed) {
            return '已完成';
        }
        if (strtotime($reminder->due_date) < time()) {
            return '已过期';
        }
        return '待提醒';
    }

    /**
     * 修改提醒
     */
    public function update(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        $reminderId = $request->param('id');
        if (empty($reminderId)) {
            return json(['status' => 400, 'message' => '提醒ID不能为空']);
        }

        // 获取提醒信息
        $reminder = Reminder::where('id', $reminderId)
            ->where('user_id', $user->id)
            ->find();

        if (!$reminder) {
            return json(['status' => 404, 'message' => '提醒不存在']);
        }

        $data = $request->post();

        try {
            // 验证提醒时间
            if (!empty($data['due_date'])) {
                if (strtotime($data['due_date']) === false) {
                    return json(['status' => 400, 'message' => '提醒时间格式不正确']);
                }
                if (strtotime($data['due_date']) < time()) {
                    return json([
                        'status' => 400,
                        'message' => '提醒时间不能早于当前时间',
                        'current_time' => date('Y-m-d H:i:s'),
                        'due_time' => $data['due_date']
                    ]);
                }
                $reminder->due_date = $data['due_date'];
            }

            // 更新基本信息
            if (isset($data['title']) && $data['title'] !== '') {
                $reminder->title = $data['title'];
            }
            if (isset($data['description'])) {
                $reminder->description = $data['description'];
            }

            // 更新循环规则
            if (isset($data['is_recurring']) && $data['is_recurring'] !== '') {
                $reminder->is_recurring = $data['is_recurring'];
            }
            if (isset($data['recurrence_rule']) && $data['recurrence_rule'] !== '') {
                if (!in_array($data['recurrence_rule'], ['daily', 'weekly', 'monthly', 'yearly'])) {
                    return json(['status' => 400, 'message' => '无效的循环规则']);
                }
                $reminder->recurrence_rule = $data['recurrence_rule'];
            }
            // 处理循环结束时间：只有在非空字符串时才进行验证和更新
            if (isset($data['recurrence_end_date']) && $data['recurrence_end_date'] !== '') {
                if (strtotime($data['recurrence_end_date']) === false) {
                    return json(['status' => 400, 'message' => '循环结束时间格式不正确']);
                }
                $reminder->recurrence_end_date = $data['recurrence_end_date'];
            } elseif (isset($data['recurrence_end_date']) && $data['recurrence_end_date'] === '') {
                // 如果传入空字符串，则清空该字段
                $reminder->recurrence_end_date = null;
            }

            // 更新项目关联
            if (isset($data['project_id'])) {
                if ($data['project_id'] === 'A') {
                    // AI自动判断项目
                    $projectId = $this->autoDetectProject($data['title'], $data['description'] ?? '');
                    $reminder->project_id = $projectId;
                    if ($projectId) {
                        $reminder->recordAiHistory('auto_project', "AI自动关联到项目ID: {$projectId}");
                    }
                } else {
                    $reminder->project_id = $data['project_id'];
                }
            }

            $reminder->save();

            // 记录操作日志
            UserController::logOperation(
                $user->id, 
                'update_reminder', 
                "修改提醒：{$reminder->title}", 
                $request
            );

            return json([
                'status' => 200,
                'message' => '提醒修改成功',
                'data' => $reminder
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('修改提醒失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '修改提醒失败：' . $e->getMessage()]);
        }
    }

    /**
     * 搜索提醒
     * @param Request $request
     * @return \think\response\Json
     */
    public function search(Request $request)
    {
        $user = $this->verifyUser($request);
        if (!$user) {
            return json(['status' => 401, 'message' => '未授权访问']);
        }

        // 获取并验证参数
        $keyword = $request->param('keyword');
        $page = max(1, intval($request->param('page', 1)));
        $pageSize = min(100, max(1, intval($request->param('page_size', 20))));
        $status = $request->param('status', 'all');
        $sort = $request->param('sort', 'due_date_desc');

        // 验证关键词
        if (empty($keyword)) {
            return json(['status' => 400, 'message' => '搜索关键词不能为空']);
        }

        try {
            // 从缓存获取结果
            $cacheKey = "reminder_search_{$user->id}_{$keyword}_{$status}_{$sort}_{$page}_{$pageSize}";
            $result = \think\facade\Cache::get($cacheKey);

            if ($result === null) {
                // 构建查询
                $query = Reminder::where('user_id', $user->id)
                    ->where(function ($query) use ($keyword) {
                        // 分割关键词
                        $keywords = explode(' ', trim($keyword));
                        foreach ($keywords as $kw) {
                            $query->where(function ($subQuery) use ($kw) {
                                $subQuery->whereOr([
                                    ['title', 'like', "%{$kw}%"],
                                    ['description', 'like', "%{$kw}%"],
                                    ['notes', 'like', "%{$kw}%"]
                                ]);
                                
                                // 修改这里：使用whereExists进行子查询
                                $subQuery->whereOr(function ($query) use ($kw) {
                                    $query->whereExists(function ($query) use ($kw) {
                                        $query->table('projects')
                                            ->whereColumn('projects.id', 'reminders.project_id')
                                            ->where('projects.name', 'like', "%{$kw}%");
                                    });
                                });
                            });
                        }
                    });

                // 状态过滤
                switch ($status) {
                    case 'waiting':
                        $query->where('is_finished', 0)
                            ->where('is_completed', 0)
                            ->where('is_disabled', 0)
                            ->where('due_date', '>', date('Y-m-d H:i:s'));
                        break;
                    case 'completed':
                        $query->where(function ($query) {
                            $query->where('is_finished', 1)
                                ->whereOr('is_completed', 1);
                        });
                        break;
                    // case 'all': 默认不加筛选
                }

                // 排序
                switch ($sort) {
                    case 'due_date_asc':
                        $query->order('due_date', 'asc');
                        break;
                    case 'due_date_desc':
                        $query->order('due_date', 'desc');
                        break;
                    default:
                        // 默认排序规则
                        $query->order([
                            'is_finished' => 'asc',
                            'is_completed' => 'asc',
                            'due_date' => 'asc',
                            'created_at' => 'desc'
                        ]);
                }

                // 分页查询
                $reminders = $query->paginate([
                    'list_rows' => $pageSize,
                    'page' => $page
                ]);

                // 格式化数据
                $formattedReminders = array_map(function ($reminder) {
                    $project = null;
                    if ($reminder->project_id) {
                        $project = Project::find($reminder->project_id);
                    }

                    return [
                        'id' => $reminder->id,
                        'title' => $reminder->title,
                        'description' => $reminder->description,
                        'due_date' => $reminder->due_date,
                        'is_recurring' => $reminder->is_recurring,
                        'recurrence_rule' => $reminder->recurrence_rule,
                        'recurrence_end_date' => $reminder->recurrence_end_date,
                        'is_finished' => $reminder->is_finished,
                        'is_completed' => $reminder->is_completed,
                        'status' => [
                            'is_overdue' => strtotime($reminder->due_date) < time(),
                            'remaining_time' => $this->calculateRemainingTime($reminder->due_date),
                            'status_text' => $this->getReminderStatus($reminder)
                        ],
                        'project' => $project ? [
                            'id' => $project->id,
                            'name' => $project->name,
                            'status' => $project->status,
                            'status_text' => Project::$statusMap[$project->status] ?? '未知状态'
                        ] : null
                    ];
                }, $reminders->items());

                $result = [
                    'total' => $reminders->total(),
                    'current_page' => $reminders->currentPage(),
                    'last_page' => $reminders->lastPage(),
                    'reminders' => $formattedReminders
                ];

                // 缓存结果5分钟
                \think\facade\Cache::set($cacheKey, $result, 300);
            }

            // 记录操作日志
            UserController::logOperation(
                $user->id,
                'search_reminder',
                "搜索提醒，关键词：{$keyword}",
                $request
            );

            return json([
                'status' => 200,
                'data' => $result
            ]);

        } catch (\Exception $e) {
            \think\facade\Log::error('搜索提醒失败：' . $e->getMessage());
            return json(['status' => 500, 'message' => '搜索失败：' . $e->getMessage()]);
        }
    }
}